# -*- coding: utf-8 -*-

import logging
import traceback

from GKModel import TutorMatch
from GKModel import OTSHelper
from utils import build_json
from utils import parse_event


def handler(event, context):
    logger = logging.getLogger()
    try:
        http_method, query_parameters, path_parameters, body, client_token, deploy_config = parse_event(event)
        ots_client = OTSHelper.create_client()
        tutor_match = TutorMatch.new(
            ots_client=ots_client,
            deploy_config=deploy_config,
            logger=logger,
            client_token=client_token
        )
        if http_method == 'GET':
            match_type = query_parameters['type'] if 'type' in query_parameters else None
            if 'create_time' in query_parameters and \
                    'category_id' in query_parameters and \
                    'mid' in query_parameters:
                next_start_primary_key = [
                    ('create_time', query_parameters['create_time']),
                    ('category_id', query_parameters['category_id']),
                    ('mid', query_parameters['mid'])
                ]
            else:
                next_start_primary_key = None
            limit = query_parameters['limit'] \
                if 'limit' in query_parameters else 10
            match_list, next_start_primary_key, client_token = tutor_match.query_match_list(
                match_type=match_type,
                next_start_primary_key=next_start_primary_key,
                limit=limit
            )
            logger.info(next_start_primary_key)
            data = {
                'list': match_list,
                'next_start_primary_key': dict(next_start_primary_key) if next_start_primary_key is not None else None,
            }
            return build_json(0, 'Success', data, client_token)
    except ValueError as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(e.args[0], e.args[1], None)
    except Exception as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(-1, str(e), None)
